// app_print.c
#include "../inc/app_print.h"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "../inc/serial_service.h"

int print_parse(int argc, char **argv)
{
    if (argc == 0)
    {
        Serial_Printf("Usage: print -s \"str\" | print -n num | print -n num1 + num2 = ? | print -m addr [length]\n");
        return -1;
    }

    if (strcmp(argv[0], "-h") == 0)
    {
        Serial_Printf("print -s \"str\": print a string\n");
        Serial_Printf("print -n num: print a number\n");
        Serial_Printf("print -n num1 + num2 = ?: print sum\n");
        Serial_Printf("print -m addr [length]: print memory at address\n");
        return 0;
    }

    if (strcmp(argv[0], "-s") == 0 && argc == 2)
    {
        Serial_Printf("%s\r\n",argv[1]);
        return 0;
    }

    if (strcmp(argv[0], "-n") == 0 && argc >= 6 && strcmp(argv[4], "=") == 0 && strcmp(argv[5], "?") == 0)
    {
        long  num1 = strtol(argv[1], NULL, 0);
        long  num2 = strtol(argv[3], NULL, 0);
        char *op   = argv[2];

        if (strcmp(op, "+") == 0)
        {
            Serial_Printf("%ld\n", num1 + num2);
            return 0;
        }
        else if (strcmp(op, "-") == 0)
        {
            Serial_Printf("%ld\n", num1 - num2);
            return 0;
        }
        else if (strcmp(op, "*") == 0)
        {
            Serial_Printf("%ld\n", num1 * num2);
            return 0;
        }
        else if (strcmp(op, "/") == 0 && num2 != 0)
        {
            Serial_Printf("%ld\n", num1 / num2);
            return 0;
        }
        else
        {
            Serial_Printf("Invalid operation or division by zero\n");
            return -1;
        }
    }

    if (strcmp(argv[0], "-m") == 0 && argc >= 2)
    {
        unsigned long addr   = strtoul(argv[1], NULL, 16);
        size_t        length = 1;

        if (argc >= 3)
        {
            length = (size_t)strtoul(argv[2], NULL, 0);
        }

        uint8_t *ptr = (uint8_t *)addr;

        Serial_Printf("Memory at 0x%lX (%zu bytes):\n", addr, length);
        for (size_t i = 0; i < length; i++)
        {
            Serial_Printf("0x%02X ", ptr[i]);
            if ((i + 1) % 16 == 0)
                Serial_Printf("\n");
        }
        if (length % 16 != 0)
            Serial_Printf("\n");

        return 0;
    }

    if (strcmp(argv[0], "-x") == 0 && argc == 2)
    {
        long num = strtol(argv[1], NULL, 0);
        Serial_Printf("0x%lX\n", num);
        return 0;
    }

    Serial_Printf("Invalid arguments\n");
    return -1;
}